package com.magicalcoder.pigeon.server;

import com.magicalcoder.pigeon.common.callback.NettyStartSuccessCallback;
import com.magicalcoder.pigeon.common.message.PigeonDecoder;
import com.magicalcoder.pigeon.common.message.PigeonEncoder;
import com.magicalcoder.pigeon.common.message.PigeonRequest;
import com.magicalcoder.pigeon.common.message.PigeonResponse;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * Created by hzhedongyu on 2017/5/24.
 */
public class PigeonNettyServer {

    private Logger logger = LoggerFactory.getLogger(PigeonNettyServer.class);

    private Map<String,Object> serviceImplBeanMap;

    public PigeonNettyServer(Map<String, Object> serviceImplBeanMap) {
        this.serviceImplBeanMap = serviceImplBeanMap;
    }

    public void start(int port, NettyStartSuccessCallback callback) throws InterruptedException {
        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup worker = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(boss,worker)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG,100)
                    .childOption(ChannelOption.SO_KEEPALIVE,true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline()
                                    .addLast(new LengthFieldBasedFrameDecoder(65536,0,4,0,0))
                                    .addLast(new PigeonDecoder(PigeonRequest.class))
                                    .addLast(new PigeonEncoder(PigeonResponse.class))
                                    .addLast(new ServerHandler(serviceImplBeanMap))
                            ;
                        }
                    })
            ;
            ChannelFuture future = b.bind(port).sync();
            future.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    logger.info("server 启动成功 端口号:"+port);
                    if(callback!=null){
                        callback.call();
                    }
                }
            });
            future.channel().closeFuture().sync();
        }finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
            logger.info("server 关闭成功");
        }
    }

}
